/*
 * common.js
 *
 * Widget Framework JavaScript routines.
 *
 */

	/*
	 * Global Objects
	 */
    var lang = new langs();
    var wfc_message = new WFMessage($('message'));
	var wfc_mainScreen;			// main screen object
	var wfc_widgetDataObj;			// main widget data object
	var wfc_ProxyObj;			// Proxy-Request Object
	var wfc_globalModules = [];	// global modules
	var wfc_addwidgets_window;		// the addWidget window object
    var wfc_has_minwidth = true; // indicate if min-width works correctly
    var wfc_layout = []; //Page Layout
	var wfc_cssloaded = []; //have loaded css array
    var wfc_servercgi_widgetlist = homeBase+'widgetList.php';
    var wfc_component_list = [];
    var wfc_component_cssloaded = [];
    var wfc_script_loaded = [];
	var wfc_remember_lasttab = ["dashBoard","dashBoard2"];	

    /**************************pageSettings.js**************************/
    //max height for modal : 1 means 100% of body height, 0.9 means 90% of body height
    if(!wf_modalMaxHeight){var wf_modalMaxHeight = 1;}
    if(!wfc_modalOffsetX){var wfc_modalOffsetX = 0;}
    if(!wfc_modalOffsetY){var wfc_modalOffsetY = 0;}
    if($chk(wfc_widgetXScrollbar)){var wfc_widgetXScrollbar = true;}
    if(!wfc_iframe_minHeight){var wfc_iframe_minHeight = 500;}
    if(!wfc_iframe_modal_top){var wfc_iframe_modal_top = 5;}
    if(!wfc_mapping_lang){var wfc_mapping_lang = false;}
    if(!wfc_customized_layout){var wfc_customized_layout = false;}
    if(!wfc_listWidgetNumber || (wfc_listWidgetNumber != 5 && wfc_listWidgetNumber != 10 && wfc_listWidgetNumber != 20 &&
           wfc_listWidgetNumber != 50)){var wfc_listWidgetNumber = 10;}

    if(!wfc_defaultWidgetHeight){var wfc_defaultWidgetHeight = 200;}
    if(!wfc_icon_L10N){var wfc_icon_L10N = false;}
    if(!wfc_widget_component_and_configure_widget_message_container){var wfc_widget_component_and_configure_widget_message_container = ['dashBoard'];}
    if(!wfc_qa_test){var wfc_qa_test = false;}
    if(!wfc_use_jquery_common_ui){var wfc_use_jquery_common_ui = false;}
	/*
	 *
	 */
	var iundefined=undefined;

	/*
	 * weird variables and functions (should be removed)
	 * (For now, we don't delete, we just move these variables and functions here to test.)
	 */
	/*
	var str = '';
 	var info='';
	*/
/* commented by TT (20090622)
	function removeWidgets(wid, pid)
	{
		//sendData(dbHandler, "act=module&data=delete&pid="+ pid +"&wid="+wid, gonull);
		sendData(dbHandler, JSON.encode({act:'moduledelete', pid:pid, wid:wid}), gonull);
	}
*/


	//////////////////////////////////////////////////////
  	var ud = "";
	var pc = 1;
	var uid = '';
	var wincount =0;
	var modules = new Array();
	var origtop = 0;
	var origleft = 0;
	var optopen = "";
	var currTabIcon = "";
	var currTabNumb = 0;
	var currTabTitle = "";
	var currTabLayout = "";
	var modList = new Hash();
	var ath;
	var dragging = false;
	var dragwhich =null;
	var dragcord = 0;
	var dragtarget = null;
	var cloneshown = false;
	var cloneunder = null;
	var cloneover = null;
	var cloneinside = null;
	var dontfire = false;
	var dragstep = 0;
	var iambz = false;

	var ipreset=false;

	var includedJs = new Array();

	var sLanguages="";
	var icn ="";
  	//var showModules=false;
	var oldPC;

	var visitedTabs = new Array();
    var inCompleteTabs = new Array();    //tabs which didn't completely rendered

	var activeTab=0;

	var tabs="";
	var widgets="";

	var activeTabModule;

	var spla, splb;

	var pgWidgets=0;		//counter per page how many widgets are there.
	var pgWidgetsTotal=0;		//counter per page how many widgets are there.
    var intAddWidgetNumber = 0;  //counter for adding widget number in add widget page
    var wfc_widget_list = [];      //widgets which have been included in tabs
    var calltime = 0;   //counter for widget_load event


	var allowClick=true;	//decides if the clikcing between is allowedn when teh ajax is still loading.
	var intWidgetTitleEllipsisDefaultWidth = 96;
    var intWidgetMinWidth = 200;

	/// show the available themes
	function show_themes(){
		new modThemes();
	}

	// show message in global
	function wfc_error_msg(msg, msg_option) {
        var option = {
            type: '0',
            description: msg,
            close: true
        };
        wfc_message.fireEvent('message',option);
	}

	/// change tab icon
	function change_icon(icn){
		if(icn != '') $('tab_icon'+currTabNumb).innerHTML = "<img id='tab_icon_icn"+currTabNumb+"' src='img/default/"+icn+"'>";
		else $('tab_icon'+currTabNumb).innerHTML ='';
		currTabIcon = icn;
		wfc_mainScreen.savePages();
	}
	//////// hide all plugin boxes
	function hide_all(){
		var blocks = $('contenttable'+wfc_mainScreen.currActive).getElements('div[id^=fdiv]');
		var c = blocks.length;

		for(var i = 0 ; i < c ; i++){
			if( blocks[i].id != "fdiv" ) {
				minimize(blocks[i].id);
			}
		}
	}


	//////// show all plugin boxes
	function max_all(){
		var blocks = $('contenttable'+wfc_mainScreen.currActive).getElements('div[id^=fdiv]');
		var c = blocks.length;

		for(var i = 0 ; i < c ; i++){
			if( blocks[i].id != "fdiv" ) {
				maximize(blocks[i].id);
			}
		}
	}

	//////// maximize a plugin box
        function maximize(which){
                var numb = which.replace(/fdiv/i , "");
                var btn_status = $('adivboxt'+numb).getProperty('class');
                if (btn_status == 'btn_hide' || btn_status == 'blank' || btn_status == 'blank_hide')
                        return;
                toggleview('adivboxt'+numb);
        }

        //////// mainimize a plugin box
        function minimize(which){
                var numb = which.replace(/fdiv/i , "");
                var btn_status = $('adivboxt'+numb).getProperty('class');
                if (btn_status == 'btn_show' || btn_status == 'blank_show')
                        return;
                toggleview('adivboxt'+numb);
        }


	// When min/max widget. No Slide visual effect, just show and hide
	function NormalToggleView(which){
		var numb = which.replace(/adivboxt/i , "");
		var con = 'insetdiv2' + numb;
		var foot = 'fdiv' + numb;
		var sbox = 'sbox' + numb;

   		if( $(con).getStyle('display') == 'block' || $(con).getStyle('display') == ''){
    			$(con).setStyle('display' , 'none');
	    		$(foot).setStyle('display' , 'none');

		    	$('adivboxt'+numb).setProperty('class', 'btn_show');
			    $('adivboxt'+numb).setProperty('title', lang.label('widget_btn_max'));
	    }else{
    			$(con).setStyle('display' , 'block');
	    		$(foot).setStyle('display' , 'block');

		    	$('adivboxt'+numb).setProperty('class', 'btn_hide');
			    $('adivboxt'+numb).setProperty('title', lang.label('widget_btn_min'));
			   	$(sbox).fireEvent('AfterMax');
		}
	}

        // When min/max widget, use vertical slide effect to show and hide window

        function SlideToggleView(which){
            var numb = which.replace(/adivboxt/i , "");
            var con = 'insetdiv2' + numb;
            var foot = 'fdiv' + numb;
			var sbox = 'sbox' + numb;
            // must make sure the style("Height") must be auto
            var heightStyle = $(con).getStyle("height");
            if (heightStyle != "auto")
                $(con).setStyle("height", "auto");

            var btn_status = $('adivboxt'+numb).getProperty('class');
        var vSlide = new Fx.Slide($(con));
        vSlide.addEvent('complete', function() {
            // event handler when slide effect completed. (hide foot and change icons).
            vSlide.wrapper.setStyle('height' , 'auto');
            if (btn_status == 'btn_hide') {
//                      $(con).setStyle('display' , 'none');
			   if($chk($(foot)))
                        	$(foot).setStyle('display' , 'none');
                        if($chk(	$('adivboxt'+numb)))
                        {
                        	$('adivboxt'+numb).setProperty('class', 'btn_show');
                        	$('adivboxt'+numb).setProperty('title', lang.label('widget_btn_max'));
                        }
                }else if(btn_status == 'blank' || btn_status == 'blank_hide')
                 {
                 	    if($chk($(foot)))
                         	$(foot).setStyle('display' , 'none');
                         if($chk($('adivboxt'+numb)))
                         	$('adivboxt'+numb).setProperty('class', 'blank_show');
                 }else if(btn_status == 'blank_show')
                 {
                 	    if($chk($(foot)))
                         	$(foot).setStyle('display' , 'block');
                         if($chk($('adivboxt'+numb)))
                         	$('adivboxt'+numb).setProperty('class', 'blank_hide');
                         if($chk($(sbox)))
                        	$(sbox).fireEvent('AfterMax');
                }else{
//                  $(con).setStyle('display' , 'block');
			   if($chk($(foot)))
                	   	$(foot).setStyle('display' , 'block');
                        if($chk($('adivboxt'+numb)))
                        {
                        	$('adivboxt'+numb).setProperty('class', 'btn_hide');
                        	$('adivboxt'+numb).setProperty('title', lang.label('widget_btn_min'));
                        }
                        if($chk($(sbox)))
                        	$(sbox).fireEvent('AfterMax');
                }
                return;
             });
	     $(con).parentNode.setStyle('position','relative').setStyle('z-index','10');
             if (btn_status == 'btn_hide' || btn_status == 'blank_hide' || btn_status == 'blank')
                vSlide.slideOut();
             else
                vSlide.slideIn();
    } // end of SlideToggleView


	// When min/max widget; toggle minimize or maximize of the plugin box
	function toggleview(which){
//	    var which = e.target.id;
		var numb = which.replace(/adivboxt/i , "");
		var con = 'insetdiv2' + numb;
		var islessIE7=false;

		// slide effect only support mootools 1.2
        if (MooTools['version'].contains('1.2') != true)
            NormalToggleView(which);    // not 1.2 just do normal toggle view.
        else {  // when 1.2 and define SlideEnable=false will use normal toggle view.
        	 //detect less than IE 7 or not
        	  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		 	var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 			if (ieversion<7)
				   islessIE7=true;
		 }

	        if ( wfc_minmaxslide_effectOnOff ==false ||  islessIE7)
	            NormalToggleView(which);    // just show and hide the content window
	        else    // default mootools 1.2 has slide effect
	            SlideToggleView(which);     // use slide visual effet to show and hide the content window
	    }
	}

	///// show the list of modules available
	function add_modules(obj){
			wfc_addwidgets_window = new modModules(obj);
	}

	/////// initilize document and set the header links based on language
	function initDocument()
	{
        //reset iframe height        
        WF.util.setIFrameHeight();
		// main screen object
		wfc_mainScreen = new Canvases();
		// main widget data object
		wfc_widgetDataObj = new WFData();
		wfc_ProxyObj = new WFProxy();

		// TODO: check WFData error
		/*
		var myUdata = wfc_widgetDataObj.getMyUdata(4);
		var myMod = wfc_widgetDataObj.getMyUdata_field(4,'modname');
		var myPdata = wfc_widgetDataObj.getMyPdata(2);
		var myPageName = wfc_widgetDataObj.getMyPdata_field(2,'pageName');
		var myTheme = wfc_widgetDataObj.getMyTheme();
		var myLang = wfc_widgetDataObj.getMyLang();
		var myWdata = wfc_widgetDataObj.getMyWdata(4);
		var myWdata_setting = wfc_widgetDataObj.getMyWdataData(4);
		var myWdata_pid = wfc_widgetDataObj.getMyWdataPid(4);
		*/

		//get the object of auth
		ath = new modLogin(true);

		// get the theme from the pageSettings.js
		$each(themeSetting.theme, function(obj, n){
			themes[n] = obj.name;
			loadCSS(obj.name);
		});

		// footer
		if (wfc_DisplayPageFooterLanguage)
		{
			$each(languageSetting.language, function(obj, n){
				icn = "img/default/"+ obj.iso +".gif";
				sLanguages+= "&nbsp;&nbsp;<a class=\"footer_link\" href=\"javascript:lang.changeLang('"+ obj.iso +"')\"><img style=\"height: 12px; border: 0; vertical-align: bottom;\" src=\" "+ icn +"\" />&nbsp;"+ obj.name +"</a>";
			});
		}

		if(sLanguages)
			$('divLanguages').setHTML(sLanguages);

 		if (window.ie6)
 		{
 			//Roger 6/16/2009 This will fix IE 6 basic setting issue
 			if($chk($("page_header")))
 				$("page_header").setStyle("height","0");
 			if($chk($("dvLogin")))
				$("dvLogin").setStyle("height","0");
		}

	    // Help Link
	    if ($defined($('help_link')))
	    {
		    $('help_link').setProperty('title',lang.label('help')).addEvent('click',function(){
		        // Help start event goes here
		        window.open( wfc_help_file_location, '');
		    });
		}
	}


	/// eval an expression indirectly
	function evalit(str){
		eval(str);
	}


	// save user data , if logged in also send to db
	function saveUD()
	{
	 	//str="";
	 	var udataArray = new Array();
	 	var nIdx = 0;

		activeTabModule = wfc_globalModules[wfc_mainScreen.currActive];

		//alert(activeTabModule);

		if(activeTabModule) {
			activeTabModule.each(function(module, id)
			{
				if($defined(module))
				{
					var info = getPos(module, wfc_mainScreen.currActive, id);

					if($defined(info))
					{
						//str += info.name + ':' + info.col + ':' + info.id + ':' + info.showMin +':'+ info.showClose +':'+ info.showSetting +':'+ info.allowDrag +':'+ info.uniqueCss +':'+ wfc_mainScreen.currActive +':'+ info.order + "|";
						udataArray[nIdx] = {modname:info.name, column:info.col, wid:info.id, showMin:info.showMin, showClose:info.showClose, showSetting:info.showSetting, showHelp:info.showHelp, allowDrag:info.allowDrag, UniqueCss:info.uniqueCss, page:wfc_mainScreen.currActive, order:info.order };
						nIdx++;
					}
				}
			});
		}


		//alert(' str '+ str );

	 	////// save the pages and names, icon, layout etc
		wfc_mainScreen.savePages();

		////// if user is logged in, it needs to be saved in the db as well..
		if(ud == "ok"){		//if logged in-- then save it into the db. thats all
			//str +='&pid='+wfc_mainScreen.currActive;
			//sendData(dbHandler, "act=udata&data="+str, gonull);
			sendData(dbHandler, JSON.encode({act:'udata', pid:wfc_mainScreen.currActive, udata:udataArray}), gonull);
		}

		iambz = false;
	}


	function getPos(mod, activeTab, id)
	{
	     if(mod.boxObject)
		 {
			    var i ;
			    var tdx = mod.boxObject.getParent();

			    if(tdx)
		        {
			        var tds = tdx.id;

			        var the_length=tds.length;
			        var tdn=tds.charAt(the_length-1);
			        var tc = tds.substr(4,(the_length - 5));
			        var childs = tdx.getChildren();
			        var l = childs.length;
			        var pn = "";
			        var lo = "";
			        var pageNumber;

			        pageNumber = activeTab;

			        ////////// find column number by going through the columns
			        //colNumber = (tdn*1)+1;
			        colNumber = (tdn*1);
			        for(i = 0 ; i < l ; i++) {
				        if(childs[i].id == mod.boxObject.id) break;
			        }
			        ordering = i+1;

			        // create an object to return
			        var obj = new Object;
			        obj.pn = pn;
			        obj.layout = lo;
			        obj.page = pageNumber;
			        obj.col = colNumber;
			        obj.order = ordering;
			        obj.name = mod.options.name;
					obj.id=mod.myid;
			        var rawHTML = mod.boxObject.innerHTML;

			        //new config
			        //get the setting of this widget.
			        var wid_conf = rawHTML;	//childs[0].innerHTML;
			        var wid_conf1;
			        var widget_config;
					wid_conf1 = wid_conf.split("`~;");
					widget_config = wid_conf1[1].split("`~;");

			        var final_setting = widget_config[0].split("~");
			        obj.showMin = final_setting[0];
			        obj.showClose = final_setting[1];
			        obj.showSetting = final_setting[2];
			        obj.showHelp = final_setting[3];
			        obj.allowDrag = final_setting[4];
			        obj.uniqueCss= final_setting[5];

			        return obj;
			   }
			   else
			     return null;
			}else
			    return null;
	}


	/// just here for debugging of ajax requests
	function gonull(request){}

	/**
	 *	\brief	Provide default Response Err message when caller do not handle any failuer case
	*/
	function ResponseERR_Default(datatxt, dataobj)
	{
		wfc_error_msg(lang.label("errorcode_"+dataobj.errcode));
	}
	var objProxyPoolSendData = {},
    sendObj,
    pool_id = '',
    key = '';
	/// send ajax data
	function sendData(url, data2 , oncomplete, VoidObj){
		if(data2.indexOf("pool_id") != -1){
			var data2_decode = JSON.decode(data2);
			pool_id = data2_decode.pool_id;
			key = url+data2+'pool_id'+pool_id;
		}
		if(pool_id && objProxyPoolSendData[key] !== undefined && objProxyPoolSendData[key]['data2'] == data2){ //If use objProxyPool && proxyObj exists in pool
			sendObj = objProxyPoolSendData[key];
			//console.log('pool::');
			//console.log(sendObj);
			// user can change oncomplete if re-send the request
			if(sendObj['$events'] !== undefined){
				if(sendObj['$events']['complete'] !== undefined && sendObj['$events']['complete'][0] !== undefined){
					sendObj['$events']['complete'][0] = oncomplete;
				}
			}
		}else{
			//console.log('new::');
			//console.log(sendObj);
			sendObj = new WFRequest.JSON();
			sendObj.setOptions({serverCGI: wfc_servercgi_wftalk, async: true, data:data2, VoidObj:VoidObj});
			// set server cgi
			sendObj.setServerCGI(url);
			// handlers
			sendObj.addEvents({onComplete:oncomplete.bind(sendObj)});
			if (oncomplete == gonull)
				sendObj.addEvents({onResponseERR:ResponseERR_Default});
			
			if(pool_id){
				//Save to objProxyPool
				objProxyPoolSendData[key] = sendObj;
				objProxyPoolSendData[key]['data2'] = data2;
			}
		}
		// send
		sendObj.send();
	}


	// show new password window
	function iWantNewPass(){
	}

	// show login window
	function iWantToLogin(){
		var w = new modLogin();
	}

	/// show register window
	function iWantToRegister(){
	}


	//remove all cookies set by this application

	function cookieClear()
	{
	  	var cookie = document.cookie.split(/;\s*/);

	  	for(var i=0;i<cookie.length;i++){
			var cName = cookie[i].split('=')[0];
		 	if(cName!="LANG"){
				document.cookie=cName+"=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
				document.cookie=cName+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
			}
		}
	}

	function setCookie(nm, vl)
	{
		// document.cookie=nm+"="+escape(vl);
	}

	/// logout , clear cookies and reload
	function iWantToLogout()
	{
		cookieClear();
		refreshPage();
	}

	var lastID=1;

	///// check user status , based on that show/hide links in header
	function checkAuth(status)
	{
		if(status == 'V')
		{
            /*
			$('header_signin').style.display = 'none';
			$('header_signup').style.display = 'none';
			$('header_changepass').style.display = '';
			$('header_signout').style.display = '';
			*/
            ud = "ok";
		}
		else if(status == 'F')
		{
			/*
			$('header_signout').style.display = 'none';
			$('header_signup').style.display = '';
			$('header_changepass').style.display = 'none';
			$('header_signin').style.display = '';
			*/
			$$('.wrap_tab_settings').setStyle('display','none');
			wfc_mainScreen.clear();
			// TT
			cookieClear();
//			location.assign('/');
		}

		//if the user is logged in
		if(userID=="" || status == 'F') {
			if( wfc_standalone ) {
				$('page_body').setHTML(" <br /> <br /> <center> <div class='notLoggedIn'>"+  lang.label('beforeLoginMessage') +"<br /><br /><a href='javascript:iWantToRegister();'>"+ lang.label('auth_process_reg_btn') +"</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='javascript:iWantToLogin();'>"+ lang.label('auth_lnk_sign_in') +"</a> </div> </center> ");
				//$('dvLogin').setStyle("display", "none");
				$('tab_panel').setStyle("display", "none");
			} else {
				// TT.20090701: When we integrate with product, we don't show 'sign-in/sign-up'.
				$('page_body').setHTML(" <br /> <br /> <center> <div class='notLoggedIn'>"+  lang.label('errorcode_100') +"<br /><br /> </div> </center> ");
			}
		} else {
			//usual header text change procedure
			wfc_SetText('add_widget_btn', 'menu_title');
			wfc_SetText('opt_link', 'basic_settings');
			wfc_SetText('server_visib', 'server_setting');
			//wfc_SetText('new_tab_btn', 'new_tab');
			wfc_SetText('header_minimize', '_hide_all');
			wfc_SetText('header_maximize', '_show_all');
			wfc_SetText('header_signin', 'auth_lnk_sign_in');
			wfc_SetText('header_signout', 'auth_lnk_sign_out');
			wfc_SetText('header_signup', 'auth_process_reg_btn');
			wfc_SetText('header_changepass', 'auth_change_pass');
			wfc_SetText('header_themes', 'settings_themes');
            //$('opt_link').setProperty('title', $('opt_link').get('text'));
            $('server_visib').setProperty('title', $('server_visib').get('text'));
		}
		////// set the theme
		setTheme();
		////// calculate and draw out user data based on info stored in cookies
 		if(tabs != "")   //create tabs
		{
			var spages = tabs.split("<||>");
			var cm="";
		    var eventCode = undefined;
			var pTitle="";
			var isPreset="";
			var pgTitle="";
		 	var x;
		 	var bPageExist = false;

			lastTab = Cookie.get("lastTab",{path: wf_cookie_path});

			for(var x = 0 ; x < spages.length; x++)
			{
				if(spages[x] != "")
				{
					parts = spages[x].split("<::>");
					parts[0] = parts[0]*1;

					if(parts[0] !="")       //check the MODULE NAME to check if its not fake or empty
					{
						if (lastTab && (lastTab == parts[8]))
							bPageExist = true;

						if( $defined(parts[7]) )
							eventCode = "'"+ parts[7] +"'";

						pTitle = parts[1].split("~");
						isPreset = false;
						pgTitle="";

						if(pTitle[1] =="PSP")
						{
							isPreset = true;
							pgTitle  = lang.label( 'presetPage'+ (x+1) );
						}
						else
						{
							isPreset=false;
							pgTitle = parts[1];
						}

						//tab is created
                     	cm = " wfc_mainScreen.addCanvas('" + JSEncodex(pgTitle) + "' , '" + parts[2] + "' , '" + parts[3] + "', "+ parts[4] +","+ parts[5] +", "+ parts[6] +", "+ eventCode +", "+ iundefined +","+ parts[8] +", "+ isPreset +", "+ false +", '"+ parts[9] +"', " + parts[10] +", " + parts[11] +", " + parts[12] +"); ";
						setTimeout('eval("'+cm+'");', 50);
				    }
				}
		    }

		 	if(lastTab && bPageExist){
				setTimeout("wfc_mainScreen.activeCanvas('tab_title"+ lastTab +"', 'load');", 50);
			}else{
				setTimeout("ShowFirstTab()", 50);
			}
			// autostart timer slide show if slide show number > 1
		 	//setTimeout("WF.util.doTimerSlideShow()",50);
			pgWidgets=0;

			//create widgets for ONLY this page.
			//createFirstTabWidgets(lastTab, false);
		}

		///// show the page and remove the loading message after everything is loaded after some time.
		setTimeout("displayPage()", 50);
	}

	function ShowFirstTab()
	{
		lastTab = GetFirstTabID();
		if (lastTab > 0)
			setTimeout("wfc_mainScreen.activeCanvas('tab_title"+lastTab+"', 'load');", 50);
		else
			setTimeout("ShowFirstTab()", 50);
	}

	var totalWids=0;
	var tempWids=1;

	function createFirstTabWidgets(lt, fromPage)
	{
		lastTab=lt;

		if(widgets !="")
		{
			if(fromPage) {
				p = widgets.split("|");

				if(p)
				{
					totalWids = p.length;

					p.each(function(widget, id)
					{
						if(widget!="" ) {
							widgetParts = widget.split(":");
							createWidgets();
						}
					});
				}
			}
			else
				createDynamicWidgets();
		}
		else{
			allowClick=true;

			//console.log(allowClick);

			if( $('tab_icon_temp'+ wfc_mainScreen.currActive) ) $('tab_icon_temp'+ wfc_mainScreen.currActive).remove();
			if( $('tab_icon_icn'+wfc_mainScreen.currActive) ) $('tab_icon_icn'+wfc_mainScreen.currActive).setStyle('display', 'block');
		}

		lastID = Cookie.get("lastID",{path: wf_cookie_path});

		//to count to see if the user has added some wids..
		oldPC = lastID;

		if(lastID) pc = parseInt(lastID)+1; else pc=1;

		//set first tab as viewed.. because it is active by default
		if (!isInArray(visitedTabs, lastTab))
			visitedTabs.push(lastTab);

		var cname = Cookie.get("cname",{path: wf_cookie_path});
		if(wfc_remember_lasttab.contains(cname))
		{
			Cookie.set("lastTab", lastTab, {path: wf_cookie_path});
		}
	}


	function createGlobal(pg)
	{
	 	wfc_globalModules[pg] = modules;
		allowClick=true;

		//setTimeout( " saveUD();", 1000);
	}


	//including js dynamically
	var newScript;
	var moduleCode="";
	var isJsExists =false;
	var oHead;
    var oScript;
    var url, ll, fileref;

	function createWidgets(x, ert){
		tempWids++;

	 	if(tempWids == totalWids){
			setTimeout( " createDynamicWidgets(); ", 500);
		}
	}


	 function createDynamicWidgets()
	 {
	 		p = widgets.split("|");
			modules =[];
            pgWidgets = 0;
            var arrAddWidget = [];
			if(p)
			{
				p.sort(sortLoadingWidgets);
			 	p.each(function(widget, id)
				{
					if(widget!="" ) {
						widgetParts = widget.split(":");
                        if (widgetParts[9] == currTabNumb) {
                            var objWidget = new Object();
                            objWidget.modname = widgetParts[0];
                            objWidget.column = widgetParts[1];
                            objWidget.wid = widgetParts[2];
                            objWidget.page = widgetParts[9];
                            objWidget.order = widgetParts[10];
                            objWidget.widget_key = widgetParts[11];
                            arrAddWidget.push(objWidget);
                        }
					}
				});
                        WF.util.includeWidgetJS(arrAddWidget);
                createGlobal(lastTab);

				tempWids=1;
			}


			//totla count is required.
			pgWidgetsTotal = pgWidgets;

			//alert('when loaded : '+ pgWidgetsTotal)
			if( $('tab_icon_temp'+ wfc_mainScreen.currActive) ) $('tab_icon_temp'+ wfc_mainScreen.currActive).remove();
			if( $('tab_icon_icn'+wfc_mainScreen.currActive) ) $('tab_icon_icn'+wfc_mainScreen.currActive).setStyle('display', 'block');
	 }

    function isInArray(ob, val)
    {
         var r=false;

         for(i=0; i <= ob.length ; i++)
         {
			 if(ob[i] == val)
             {
                r = true;
                break;
             }
		}

        return r;
    }

    function getFullHeight()
    {
       	var sc =  window.screen.height;
	   	var doc = document.body.clientHeight;
	   	var h, x, fnl;

	   	//chcek the screen and document height is same
	   	if(sc > doc) h=sc; else h = doc;

		//chcek the height of the div which is openend
		x = $('modaloverlay').getSize().scrollSize.y+120;

		if(x >h) fnl = x; else fnl=h;

	   	return fnl;
    }


	function getLastID(ud)
	{
		var lastID=1;
		var tmp;

		if(ud)
		{
			tmp = ud.split("|");
		 	tmp.sort(sortReadingWidgets);

			if(tmp !=undefined){
				var x = tmp[0].split(":");
				lastID=x[2];
			}

			lastID = parseInt(lastID)+1;
		}

		return lastID;
	}


	//this is used while calling from the checkAuth function to sort the widgets and draw them in the pagw
	function sortLoadingWidgets(a, b)
	{
		if(a !="" && b !="" ) {
			spla=a.split(":");
			splb=b.split(":");

			if(spla[10]=='undefined' || splb[10]=='undefined' ) {
				return 1;
			}
			else {
				 return spla[10] - splb[10];
			}
		}
		else
			return 1;			//equal
	}

	//this is used while calling from the lastUD function
	function sortTabsNumbers(a, b)
	{
	 	if(a!="" && b!="")
			return b-a;		//decending
		else
			return 0;
	}


	//this is used while calling from the lastUD function
	function sortReadingWidgets(a, b)
	{
	 	if(a !="" && b !="" ) {
			spla=a.split(":");
			splb=b.split(":");

	 		if(spla[2]=='undefined' || splb[2]=='undefined' || isNaN(spla[2]) || isNaN(splb[2]))
				return splb[2] - spla[2];		//decending
			else
				return 0;
		}
		else
			return 0;			//equal
	}


	function remWids(id)
	{
		tempAdded[id] = 0;
		pgWidgets = (pgWidgets-1);
	}


	var tempAdded = new Array();	//global var for temporaryly added widst

	function addWidgets(id, nmwa)
	{
 		// cancel added widgets
    	if(tempAdded[id]==nmwa) {
        		if(!$('wid_chk_'+id).checked){
            	//console.log('canceling widget ' + id);
            	remWids(id);
        		}
        	return ;
    	}
        if(pgWidgets >= wfc_widgetLimit){
			wfc_error_msg(lang.label('not_more_than_30'));
			$each($$('input[id^=wid_chk]'),function(item,key){
				if(item.id.split("_")[2]==id)
					item.checked=false;
			});
			return;
		}

		pgWidgets ++;
		tempAdded[id] = nmwa;
	}


	function saveWidgets()
	{
	    // Terrence 12/03/09, for table style layout.
	    if (wfc_is_table_layout_style(currTabLayout)) {
	        wfc_saveWidgets_table_layout_style();
	        return;
	    }
	    /////////////////////////////////////////////////////////////////////////////////////////////////
		var iJs="";
		var udataArray = new Array();
		var wdataArray = new Array();
		var nIdx = 0;
		var nColumns = parseInt(currTabLayout.split("-", 1)[0]);

		var callAjax=false;
		if(tempAdded.length>0)
		{
			tempAdded.each(function(module, id)
			{
				if(module !=undefined && module !="" && module !='undefined'){
					if(module!=0)
					{
						callAjax=true;
			 		    udataArray[nIdx] = {
			 		    	modname:module,
			 		    	column:nIdx%nColumns,
			 		    	order:parseInt(nIdx/nColumns)+1,
			 		    	wid:pc,
			 		    	showMin:widget_property.showMin,
			 		    	showClose:widget_property.showClose,
			 		    	showSetting:widget_property.showSetting,
			 		    	showHelp:widget_property.showHelp,
			 		    	allowDrag:widget_property.allowDrag,
			 		    	page:wfc_mainScreen.currActive
			 		    };
						//str1 += module+":"+pc+":"+ wfc_mainScreen.currActive +"|";
						wdataArray[nIdx] = {modname:module, wid:pc, data:"", pid:wfc_mainScreen.currActive};

						iJs +=module+',';

						pc++;
						nIdx++;
					}
				}
			});

			if(callAjax){
				$('reloadButton').setProperty('disabled', true);

				//find out what is the next col available.
                //useless code, should be removed
                sendData(dbHandler, JSON.encode({act:'addWidgets', pid: wfc_mainScreen.currActive, udata:udataArray, wdata:wdataArray, updatedOriginalUdata:[]}), addWidgetscallback,{iJs:iJs});

			}
			else
			{
				wfc_error_msg( lang.label('messege_reload') );
			}
		}
		else
		{
			wfc_error_msg( lang.label('messege_reload') );
		}
	}

	//function addWidgetscallback(responseString)
	function addWidgetscallback(responseObj)
	{
		var jsonObj=JSON.decode(responseObj[0]);
		if( jsonObj == null || !isset(jsonObj) || jsonObj.errcode!=0 ) {
			wfc_error_msg(lang.label("msg_addwidgetfailed"));
			// we don't refresh. we close the window instead (when error).
			wfc_addwidgets_window.closeModal();
			return;
		}

		refreshPage();
	}

	function checkRefresh(c)
	{
		if(c==true){
			if($defined ($('modaloverlay')) ) $('modaloverlay').remove();
			if($defined ($('overlay')) ) $('overlay').remove();
			return;
		}
	}

	function refreshPage()
	{
		window.parent.location.href=window.parent.location.href;
	}

	function afterLogin()
	{
		$('regMsg').setHTML(' ');
		alert(lang.label('auth_registration_ok'));
		window.location.reload(true);
	}


	/// display the page
	function displayPage()
	{
		if (DisplayPageHeader)
			$('page_header').setStyles({'display': 'block', 'min-width': wfc_pagebody_minwidth+'px'});

		if (DisplayPageHeaderMenu)
			$('server_visib').setStyle('display' , 'block');

		if (wfc_global_help_link)
			$('help_link').setStyle('display' , 'block');
        // 2= border width
		$('page_body').setStyles({'display': 'block', 'min-width': wfc_pagebody_minwidth-2+'px'});

        if(!wfc_has_minwidth) // if browser doesn't support min-width (IE6)
        {
            // set width
		$('tab_settings').getElement('div.wrap_tab_settings').setStyle('width', wfc_pagebody_minwidth-1 +'px');
            // add an image
            new Element('img',{'class':'ie6_spacer','src':'img/default/1space.gif','width':wfc_pagebody_minwidth,'height':'1'}).inject($('page_body'));
            //$('contenttable'+wfc_mainScreen.currActive).hasLayout= true;
        }

		if (DisplayPageFooter){
			$('page_footer').setStyle('display' , 'block');
		}
        $(document.body).setStyle('height','auto');
        $('loader').remove();
        $('wf_main').setStyle('display','block');
        window.fireEvent('tab_change');
	}


	////SET The Theme Based on Cookie , otherwise set to default
	function setTheme(userTheme)
	{
		var ot = userTheme;

		if(userTheme == undefined)
		{
			userTheme = Cookie.get('theme',{path: wf_cookie_path});
		}
		else
		{
			sendData(dbHandler, JSON.encode({act:'theme', theme:userTheme}), gonull);
		}

		if(userTheme == '') userTheme = 'default';

		//Cookie.set('theme', userTheme  , {duration: 365});
		Cookie.set('theme', userTheme  , {path: wf_cookie_path});

		var liner;

		if(ot!=undefined){
			liner=document.getElementById('style1');
			liner.href= $('link_'+userTheme).href;
			//alert(' -- '+ liner.href);
		}

		if(ot!=undefined)
			wfc_error_msg( lang.label('theme_set') );
        }


	var loadCSS = function(file) {
		var newlink = document.createElement('link');
		newlink.href = homeBase+WP_WEBROOT_NO_SLASH+'/theme/' + file + '/theme.css'; 
		newlink.rel = 'alternate stylesheet';
		newlink.type = 'text/css';
		newlink.id= 'link_'+file;
		//alert(file);
	 	document.getElementsByTagName('head')[0].appendChild(newlink);
	};



 function URLDecode(psEncodeString)
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

function IncludeJavaScript(jsFile)
{
	document.write('<script type="text/javascript" src="' + jsFile + '"></scr' + 'ipt>');
}

/**
 *	\brief	Javascript character escape
 *
 *	\param[in]		preescape
 *	\return			escaped string
*/
var hex=new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');

function JSEncodex(preescape)
{
	var escaped="";

	var i=0;
	for(i=0;i<preescape.length;i++)
	{
		escaped=escaped+encodeCharx(preescape.charAt(i));
	}

	return escaped;
}

function encodeCharx(original)
{
   	var found=true;
   	var thecharchar=original.charAt(0);
   	var thechar=original.charCodeAt(0);
	switch(thecharchar)
	{
		case '\n': return "\\n"; break; //newline
		case '\r': return "\\r"; break; //Carriage return
		case '\'': return "\\\\\\'"; break;
		case '"': return "\\\""; break;
		case '\&': return "\\&"; break;
		case '\\': return "\\\\\\\\"; break;
		case '\t': return "\\t"; break;
		case '\b': return "\\b"; break;
		case '\f': return "\\f"; break;

		default:
			found=false;
			break;
	}
	if(!found)
	{
		if(thechar>127)
		{
			var c=thechar;
			var a4=c%16;
			c=Math.floor(c/16);
			var a3=c%16;
			c=Math.floor(c/16);
			var a2=c%16;
			c=Math.floor(c/16);
			var a1=c%16;
		//	alert(a1);
			return "\\u"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+"";
		}
		else
		{
			return original;
		}
	}
}

/**
 *	\brief		Get First TAB ID
*/
function GetFirstTabID()
{
	var FirstTab = 0;
	var alltabs = $('tab_panel').getChildren();
	var ttabs = alltabs.length;
	for (var i = 0 ; i < ttabs ; i++)
	{
		var idd = alltabs[i].id;
		if(idd != 'tab_box' && idd.contains('tab_box'))
		{
			FirstTab = idd.replace(/tab_box/i , "");
			break;
		}
	}
	return FirstTab;
}


// this is 'all'! must calculate the width by 100% - others.
function wfc_get_all_width(bodyWidth) {
	var otherWidth;
	var currWidth;
	var icntAll;
	var w;
    var op = currTabLayout.split('-');      // get current tab layout
    var hm = op[0];
    var format = op[1];

    // calculate the layout child.
	if(hm == 1 && format == 0) currWidth = l1;
	if(hm == 2 && format == 0) currWidth = xl2;
	if(hm == 3 && format == 0) currWidth = xl3;
	if(hm == 4 && format == 0) currWidth = xl4;
	if(hm == 2 && format == 1) currWidth = xl5;
	if(hm == 3 && format == 1) currWidth = xl6;
	if(hm == 2 && format == 2) currWidth = xl7;

	// calculate 'all' width in percentage.
	var otherWidth=0;
	for(var y=0; y<currWidth.length; y++)
	{
		if(currWidth[y] !== 'all'){ // avoid 'all'
	    // check if currWidth[y] is % or not.
	        if (currWidth[y].indexOf("%") == -1) {
		        // Sum of all other width (except all).
		        otherWidth += parseInt(currWidth[y].replace("px", ""));
		    }
		    else {
		        // it is percent; transfer it to px and sum to otherWidth
		        otherWidth += parseInt(parseInt(currWidth[y].replace("%", "")) * bodyWidth / 100);
		    }
		}
	}
    w = parseInt((bodyWidth - otherWidth) * 100 / bodyWidth) + "%";
	return w;
}



// Calculate the real width of a width from the column width.
function wfc_getCurrentColumnWidth(el)
{
	if (el.boxObject == null)
		return 0;

	// Terrence 12/03/09, for table layout style.
	if (wfc_is_table_layout_style(currTabLayout))
	    return el.boxObject.getParent().clientWidth;
	///////////////////////////////////////////////////////////
    var pagebodyWidth =$('tab_settings').getStyle('width');
    var bodyWidth=pagebodyWidth.replace(/px/gi,'');
    // get the total column number
    var column_num = currTabLayout.split('-')[0];
    // get the cellspacing attribute of .panels_table
    var table = el.boxObject.getParent('.panels_table');
    var cellspacing = parseInt(table.getProperty('cellspacing'), 10)  * (parseInt(column_num,10)+1);
    // sometimes we need minus width of scrollbar, sometimes not
    var vertical_scroll = (document.body.clientHeight!=window.innerHeight) ? 0:18;
    // This mears each widget has 2px border width
    var border_w = 2;
    // correcting body width
    bodyWidth = bodyWidth - cellspacing -  border_w * parseInt(column_num,10) - vertical_scroll;
    var w0 = el.boxObject.getParent().getProperty('width'); // must use getProperty can't use getStyle. in percent
    if (w0 == null) {
        // this is 'all'! must calculate the width by 100% - others.
        w0 = wfc_get_all_width(bodyWidth);
    }
    /*
	if(window.ie6)
 	{
 		wfc_setWidgetMinWidgetForIE6(w0,el,bodyWidth);
    }
    */
    // w0 is the width of the column, either with %, px or number.
    if (w0.indexOf("%") == -1) {
        // not in percentage mode, just return the length;
        return parseInt(w0);
    }

    if(parseInt(bodyWidth) < wfc_pagebody_minwidth)
    	bodyWidth= wfc_pagebody_minwidth- cellspacing -  border_w * parseInt(column_num,10) - vertical_scroll;
    var w1 = w0.replace(/%/gi, '');                         // remove the % from w0
    var w = parseInt(bodyWidth * w1 / 100);               // calculate real width = page_width * percent
    return w;                                               // return value isin % mode
}


function wfc_setWidgetMinWidgetForIE6(widgetwidth,el,bodyWidth){
		var caption_middle=el.boxObject.getElement(".window_caption_middle");
		if(!$chk(caption_middle)) return;
    	if (widgetwidth.indexOf("%") == -1) {
        	// not in percentage mode, just return the length;
        	widgetwidth=(widgetwidth)/bodyWidth+"%";
    	}

        // var min_width =wfc_pagebody_minwidth* widgetwidth.replace('%','')/100 - 4;
        // width - window_caption_left - window_caption_right
        var min_width =wfc_pagebody_minwidth* widgetwidth.replace('%','')/100 -10;

		// img for setting min width
		var imgspace=caption_middle.getElement('.extraspace');
		if($chk(imgspace)) Element.remove(imgspace);
        var img_min = new Element('img',{'class':'extraspace','src':'img/default/1space.gif', 'width':min_width, 'height':'1'}).injectInside(caption_middle);
}

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities
    //
    // version: 903.2219
    // discuss at: http://phpjs.org/functions/htmlentities
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    if (string == undefined || string == null || string == ""){
        return "";
    }

    tmp_str = string.toString();

    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }

    return tmp_str;
}

function html_entity_decode( string, quote_style ) {
    // Convert all HTML entities to their applicable characters  
    // 
    // version: 901.714
    // discuss at: http://phpjs.org/functions/html_entity_decode
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    if (string == undefined || string == null || string == ""){
        return "";
    }
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';

    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function get_html_translation_table(table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 903.1614
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }

    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        if (useQuoteStyle != 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle == 'ENT_QUOTES') {
            entities['39'] = '&#039;';
        }
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
	    entities['38']  = '&amp;';
        if (useQuoteStyle != 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle == 'ENT_QUOTES') {
            entities['39'] = '&#039;';
        }
        entities['45']  = '&#45;';
	    entities['60']  = '&lt;';
	    entities['62']  = '&gt;';
	    entities['160'] = '&nbsp;';
	    entities['161'] = '&iexcl;';
	    entities['162'] = '&cent;';
	    entities['163'] = '&pound;';
	    entities['164'] = '&curren;';
	    entities['165'] = '&yen;';
	    entities['166'] = '&brvbar;';
	    entities['167'] = '&sect;';
	    entities['168'] = '&uml;';
	    entities['169'] = '&copy;';
	    entities['170'] = '&ordf;';
	    entities['171'] = '&laquo;';
	    entities['172'] = '&not;';
	    entities['173'] = '&shy;';
	    entities['174'] = '&reg;';
	    entities['175'] = '&macr;';
	    entities['176'] = '&deg;';
	    entities['177'] = '&plusmn;';
	    entities['178'] = '&sup2;';
	    entities['179'] = '&sup3;';
	    entities['180'] = '&acute;';
	    entities['181'] = '&micro;';
	    entities['182'] = '&para;';
	    entities['183'] = '&middot;';
	    entities['184'] = '&cedil;';
	    entities['185'] = '&sup1;';
	    entities['186'] = '&ordm;';
	    entities['187'] = '&raquo;';
	    entities['188'] = '&frac14;';
	    entities['189'] = '&frac12;';
	    entities['190'] = '&frac34;';
	    entities['191'] = '&iquest;';
	    entities['192'] = '&Agrave;';
	    entities['193'] = '&Aacute;';
	    entities['194'] = '&Acirc;';
	    entities['195'] = '&Atilde;';
	    entities['196'] = '&Auml;';
	    entities['197'] = '&Aring;';
	    entities['198'] = '&AElig;';
	    entities['199'] = '&Ccedil;';
	    entities['200'] = '&Egrave;';
	    entities['201'] = '&Eacute;';
	    entities['202'] = '&Ecirc;';
	    entities['203'] = '&Euml;';
	    entities['204'] = '&Igrave;';
	    entities['205'] = '&Iacute;';
	    entities['206'] = '&Icirc;';
	    entities['207'] = '&Iuml;';
	    entities['208'] = '&ETH;';
	    entities['209'] = '&Ntilde;';
	    entities['210'] = '&Ograve;';
	    entities['211'] = '&Oacute;';
	    entities['212'] = '&Ocirc;';
	    entities['213'] = '&Otilde;';
	    entities['214'] = '&Ouml;';
	    entities['215'] = '&times;';
	    entities['216'] = '&Oslash;';
	    entities['217'] = '&Ugrave;';
	    entities['218'] = '&Uacute;';
	    entities['219'] = '&Ucirc;';
	    entities['220'] = '&Uuml;';
	    entities['221'] = '&Yacute;';
	    entities['222'] = '&THORN;';
	    entities['223'] = '&szlig;';
	    entities['224'] = '&agrave;';
	    entities['225'] = '&aacute;';
	    entities['226'] = '&acirc;';
	    entities['227'] = '&atilde;';
	    entities['228'] = '&auml;';
	    entities['229'] = '&aring;';
	    entities['230'] = '&aelig;';
	    entities['231'] = '&ccedil;';
	    entities['232'] = '&egrave;';
	    entities['233'] = '&eacute;';
	    entities['234'] = '&ecirc;';
	    entities['235'] = '&euml;';
	    entities['236'] = '&igrave;';
	    entities['237'] = '&iacute;';
	    entities['238'] = '&icirc;';
	    entities['239'] = '&iuml;';
	    entities['240'] = '&eth;';
	    entities['241'] = '&ntilde;';
	    entities['242'] = '&ograve;';
	    entities['243'] = '&oacute;';
	    entities['244'] = '&ocirc;';
	    entities['245'] = '&otilde;';
	    entities['246'] = '&ouml;';
	    entities['247'] = '&divide;';
	    entities['248'] = '&oslash;';
	    entities['249'] = '&ugrave;';
	    entities['250'] = '&uacute;';
	    entities['251'] = '&ucirc;';
	    entities['252'] = '&uuml;';
	    entities['253'] = '&yacute;';
	    entities['254'] = '&thorn;';
	    entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    histogram[String.fromCharCode('38')] = entities['38'];
    // ascii decimals to real symbols
    for (decimal in entities) {
    	if(decimal!='38')
    	{
        	symbol = String.fromCharCode(decimal);
        	histogram[symbol] = entities[decimal];
        }
    }
    
    return histogram;
}

function wfc_SetText(id, label)
{
	if ($(id) != null)
		$(id).setHTML(lang.label(label));
}

function isset(varname) {
	return( typeof(varname) != 'undefined' );
}

function toggleMsg(a)
{
    if(a.className=='icon_show')
    {
        $(a.parentNode.parentNode).removeClass('collapsed');
        a.className = 'icon_hide';
    }else
    {
        $(a.parentNode.parentNode).addClass('collapsed');
        a.className = 'icon_show';
    }
    a.blur();
    return false;
}

function changeLineForTip(tip, lineLength){
    var changeLineTip = "";
    if (Browser.firefox && tip.length > lineLength){
        for (var i = 0; i < tip.length;){
            if (i < tip.length){
                changeLineTip += tip.substring(i, i+lineLength) + " ";
            }else{
                changeLineTip += tip.substring(i, tip.length);
            }
            i+=lineLength;
        }
    }else{
        changeLineTip = tip;
    }
    return changeLineTip;
}

Element.implement({
    hasEvent: function(eventType,fn) {
        //get the element's events
        var myEvents = this.retrieve('events');
        //can we shoot this down?
        return myEvents && myEvents[eventType] && (fn == undefined || myEvents[eventType].keys.contains(fn));
    },
    createDocumentFragment: function(){
        return document.createDocumentFragment();
    }
});